import staticRouters from "@/router/route.js";

let firstMenu = null;

export function menuToRouter(userMenus) {
  const routers = [];
  const staticRouter = staticRouters;
  const _mapRouter = (menus) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = staticRouter.find((item) => item.path === menu.url);
        if (route) {
          routers.push(route);
        }
        if (!firstMenu) {
          firstMenu = menu;
        }
      } else {
        _mapRouter(menu.children);
      }
    }
  };
  _mapRouter(userMenus);
  return routers;
}

export { firstMenu };

export function menuToPermission(userMenus) {
  const permissions = [];

  const _mapPermission = (menus) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _mapPermission(menu.children ?? []);
      } else {
        permissions.push(menu.permission);
      }
    }
  };
  _mapPermission(userMenus);
  return permissions;
}

export function menuToBreadcrumb(userMenus, currentPath) {
  const breadcrumbs = [];

  const _mapBreadcrumb = (menus) => {
    for (const menu of menus) {
      if (menu.type === 1) {
        const findMenu = _mapBreadcrumb(menu.children ?? [], currentPath);
        if (findMenu) {
          breadcrumbs.push({ name: menu.name });
          breadcrumbs.push({ name: findMenu.name });
          return findMenu;
        }
      } else if (menu.type === 2 && menu.url === currentPath) {
        return menu;
      }
    }
  };

  _mapBreadcrumb(userMenus);
  return breadcrumbs;
}
